<template>
	<view class="box2">
		<template>
			<view>
				<view class="page-body">
					<view class="page-section page-section-gap">
						<map scale="20" style="width: 100%; height: 40vh;" :latitude="latitude" :longitude="longitude"
							:enable-building="true" :polyline="polyline" :enable-satellite="true" :show-location="true"
							:markers="markers">
						</map>
					</view>
					<button @click="getCurrentLocation" >我的位置</button>
				</view>
			</view>
		</template>
		<view class="flow flex-y-center">
			<view class="line"></view>
			<view>
				<view></view>
				<view class="item flex-y-center" :key="index" v-for="(item,index) in infoList">
					<view class="dot flex-grow-0"></view>
					<view class="title" v-if="item.status!=3">
						{{getStatusText(item.status-0)}}&nbsp;<span>{{item.changeTime}}</span>
					</view>

					<view class="title" v-else-if="item.status==3&&item.currentAddressCenter.type==='2'">
						{{getStatusText(item.status-0)}}&nbsp;<span>{{item.changeTime}}</span>
					</view>
					<view class="title" v-else>
						&nbsp;<span>{{item.changeTime}}</span></view>

					<view class="flex-grow-1">

						<view class="name" v-if="item.status==0">商品已下单</view>
						<view class="name" v-else-if="item.status==1">包裹正在等待揽件</view>
						<view class="name" v-else-if="item.status==2">
							【{{item.currentAddressCenter.name}}】&nbsp;{{item.currentAddress}}&nbsp;已揽收</view>
						<view class="name" v-else-if="item.status==3">
							<view v-if="item.transitStatus==='0'">
								【{{item.currentAddressCenter.region.name}}】&nbsp;已离开&nbsp;{{item.currentAddressCenter.name}}&nbsp;;
								发往&nbsp;{{item.toAddressCenter.name}}
							</view>
							<view v-if="item.transitStatus==='1'">
								【{{item.currentAddressCenter.region.name}}】&nbsp;已到达&nbsp;{{item.currentAddressCenter.name}}
							</view>

						</view>
						<view class="name" v-else-if="item.status==4">

							【{{item.currentAddressCenter.region.name}}】&nbsp;&nbsp;{{item.currentAddressCenter.name}}&nbsp;;
							快递员&nbsp;{{postman.name}}&nbsp;<span class="phone">{{postman.phone}}</span>正在为你派件
						</view>
						<view class="name" v-else-if="item.status==5">
							你的快递已送至{{logistics.address}}，请前往取件，如有问题请联系<span
								class="phone">{{postman.phone}}</span>
						</view>
						<view class="name" v-else-if="item.status==6">你已在{{logistics.address}}完成取件，感谢你使用**物流，期待再次为你服务
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		findLogisticsById
	} from "../../../api/logistics/logistics";
	export default {
		data() {
			return {
				map: null,
				deviceId: '', //设备的唯一标识符
				id: 0, // 使用 marker点击事件 需要填写id
				title: 'map',
				latitude: 26.509558,
				longitude: 106.678995,
				info: "",
        markers: [],
				polyline: [{
					points: [],
					color: "#00ff00",
					width: 10,

					borderWidth: 15 //线的边框宽度，还有很多参数，请看文档
				}],
				logistics:{},
				infoList: [],
				postman: {},
				latestData: [],
				startDate: new Date().getTime(),
				endDate: new Date().getTime(),
			}
		},
		async created() {
			this.getLogistics()
			if (this.logistics.postman) {
				this.postman = this.logistics.postman
        this.deviceId=this.postman.deviceId
			}
			this.infoList = this.logistics.infoList
			this.infoList.reverse().forEach(l => {
				if (l.currentAddress != null) {
					if (l.status === '4') {
						if(this.startDate>new Date(l.changeTime).getTime()){
							this.startDate = new Date(l.changeTime).getTime()
						}
					}
					if (l.status === '5') {
						this.endDate =new Date(l.changeTime).getTime()
					}
					this.polyline[0].points.push({
						longitude: l.currentAddressCenter.longitude,
						latitude: l.currentAddressCenter.latitude
					})
					this.longitude = this.polyline[0].points[0].longitude
					this.latitude = this.polyline[0].points[0].latitude
          let marker={
            id: this.markers.length+1,
            width: 40,
            height: 40,
            latitude: l.currentAddressCenter.latitude,
            longitude: l.currentAddressCenter.longitude,
            iconPath: '../../static/Marker.png',
            anchor: {
              x: 0.5,
              y: 1
            }
          }
          this.markers.push(marker)
				}
			})
			this.infoList.reverse()
			console.info(this.polyline[0].points)
			var query = {
				query: {
					range: {
						date: {
							gte: this.startDate,
							lte: this.endDate
						}
					}
				}
			};
			console.info(query)
			//获取从快递员开始送件到当前时间的经纬度
			const username = 'elastic';
			const password = '123456';
			const credentials = `${username}:${password}`;
			const encodedCredentials = btoa(credentials);
			uni.request({
				url: `http://124.70.51.123:9200/${this.deviceId.toLowerCase()}/_search`,
				header: {
					'Authorization': `Basic ${encodedCredentials}`
				},
				method: 'POST',
				data: JSON.stringify(query),
				success: (response) => {
					// 处理成功响应
					console.log(response);
					let points=response.data.hits.hits
					console.info(points)
					if(points){
						points.forEach(p=>{
							this.polyline[0].points.push({
								latitude: p._source.latitude,
								longitude: p._source.longitude,
							});
						})
					}
				},
				error: (error) => {
					// 处理错误响应
					console.error("error");
				}
			});
      let marker1={
        id: this.markers.length+1,
        width: 40,
        height: 40,
        latitude: this.polyline[0].points[this.polyline[0].points.length-1].latitude,
        longitude: this.polyline[0].points[this.polyline[0].points.length-1].longitude,
        iconPath: '../../static/Marker.png',
        anchor: {
          x: 0.5,
          y: 1
        }
      }
      this.markers.push(marker1)
			// 如果快递未送达开始定时任务
			if(this.infoList&&this.infoList[0].status==="4"){
				this.startTimer() 
			}
		},
		beforeDestroy() {
			this.stopTimer() // 在页面销毁前停止定时任务
		},
		methods: {
			//从物流信息页面获取物流信息
			getLogistics(){
				const pages = getCurrentPages();
				    const currentPage = pages[pages.length - 1];
				    const options = currentPage.options;
				    const data = JSON.parse(options.data);
				this.logistics=data
			},
			//获取当前位置
			getCurrentLocation() {
			      uni.getLocation({
			        type: 'gcj02',
			        success: res => {
			          this.latitude = res.latitude
			          this.longitude = res.longitude
			        },
			        fail: err => {
			          console.log('获取位置失败:', err)
			        }
			      })
			    },
				//每3秒获取一次快递员位置信息
			startTimer() {
				this.timer = setInterval(() => {
					this.queryLatestData()
					if (this.polyline[0].points.length==0||this.polyline[0].points[this.polyline[0].points.length - 1].latitude != this.latestData
						.latitude &&this.latestData.size>0&&
						this.polyline[0].points[this.polyline[0].points.length - 1].longitude != this.latestData
						.longitude) {
						this.polyline[0].points.push({
							latitude: this.latestData.latitude,
							longitude: this.latestData.longitude,
						});
            this.markers[this.markers.length-1].latitude=this.latestData.latitude
            this.markers[this.markers.length-1].longitude=this.latestData.longitude
					}

				}, 3000) // 每隔3秒执行一次任务
			},
			stopTimer() {
				clearInterval(this.timer) // 停止定时任务
			},
			//获取ES中最新的一条数据
			queryLatestData() {
				const username = 'elastic';
				const password = '123456';
				const credentials = `${username}:${password}`;
				const encodedCredentials = btoa(credentials);

				uni.request({
					url: `http://124.70.51.123:9200/${this.deviceId.toLowerCase()}/_search`,
					header: {
						'Authorization': `Basic ${encodedCredentials}`
					},
					method: 'POST',
					data: JSON.stringify({
						query: {
							match_all: {}
						},
						sort: [{
							date: 'desc'
						}],
						size: 1
					}),
					success: (response) => {
						// 处理成功响应
						this.latestData = response.data.hits.hits[0]._source;
						console.info(this.latestData)
					},
					error: (error) => {
						// 处理错误响应
						console.error(error);
					}
				});
			},

			endsWith(str, suffix) {
				return str.endsWith(suffix);
			},
			getStatusText(status) {
				switch (status) {
					case 0:
						return "已下单";
					case 1:
						return "已发货";
					case 2:
						return "已揽件";
					case 3:
						return "运输中";
					case 4:
						return "派送中";
					case 5:
						return "待取件";
					case 6:
						return "已签收";
					default:
						return "";
				}
			}
		}
	}
</script>

<style>
	.box2 {
		background: #fff;
		margin: 0 20rpx;
		border-radius: 10rpx;
	}

	.box2 .flow {
		position: relative;
		overflow: hidden;
		margin: 20rpx 30rpx;
	}

	.box2 .flow .line {
		height: 100%;
		width: 1px;
		background: #eff0f2;
		position: absolute;
		left: 9rpx;
		z-index: 0;
	}

	.box2 .flow .item {
		margin: 38rpx 0;
	}

	.box2 .flow .item .dot {
		width: 20rpx;
		height: 20rpx;
		background: #eff0f2;
		border-radius: 50%;
		position: relative;
		margin-right: 32rpx;
		display: inline-block;
	}

	.box2 .flow .item .title {
		color: #a5a5a5;
		font-size: 1.5rem;
		display: inline-block;
	}

	.box2 .flow .item .title span {
		font-size: 1rem;
	}

	.box2 .flow .item .name {
		margin-top: 5rpx;
		color: #707070;
		margin-left: 50rpx;
		font-size: 1rem;
	}

	.box2 .flow .item .time {
		font-size: 0.75rem;
		margin-top: 5rpx;
		color: #707070;
	}

	.box2 .flow .item:nth-child(1) {
		color: #f3914b;
	}

	.box2 .flow .item:nth-child(2) .title {
		color: #f3914b;
	}

	.box2 .flow .item:nth-child(2) .name {
		color: #f3914b;
	}

	.box2 .flow .item:nth-child(2) .time {
		color: #f3914b;
	}

	.box2 .flow .item:nth-child(2) .dot {
		background: #f3914b;
	}

	.phone {
		color: #f3914b;
	}
</style>